(function ($) {
    $.fn.imgUpload = function (options) {
        var element = this;
        var files = [];
        if (!element) {
            console.log('未找到页面控件');
            return;
        } else {
            $(element).append(
                '<label class="img-container" >' +
                '<input type="file" name="files[]" class="file-input"  multiple="">' +
                '<div class="img-up-add img-item"><span class="img-add-icon">+</span></div>' +
                '</label>');
            files = [];
        }

        function uploadImg() {
            console.log(files);
            var xhr = new XMLHttpRequest();
            var formData = new FormData();

            for (var i = 0, f; f = files[i]; i++) {
                formData.append('files', f);
            }
            xhr.onreadystatechange = function (e) {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        $(element).find('.file-input').val('');
                        var json = JSON.parse(xhr.responseText);
                        setTimeout(function () {
                            options.onSuccess(json);
                        }, 500);
                    } else {
                        options.onFailure(json);
                    }
                }
            }
            xhr.open('POST', options.path, true);
            xhr.send(formData);
        };

        var addBtn = $(element).find('.img-up-add');
        addBtn.click(function () {
            var imgFileInput = $(element).find('.file-input');
            if (imgFileInput) {
                imgFileInput.value = null;
                imgFileInput.click(function (e) { });
            }
        });

        // 预览图片
        //处理input选择的图片
        function handleFileSelect(evt) {
            files = evt.target.files;
            for (var i = 0, f; f = files[i]; i++) {
                // 过滤掉非图片类型文件
                if (!f.type.match('image.*')) {
                    continue;
                }
                uploadImg();
            }
        }
        $(element).find('.file-input').on('change', handleFileSelect);


    }
})(jQuery);


